package org.edu.zzu.health_report.job;

import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.edu.zzu.health_report.domain.Record;
import org.edu.zzu.health_report.domain.User;
import org.edu.zzu.health_report.service.RecordService;
import org.edu.zzu.health_report.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author gaopeng
 * @date 2021/11/10
 **/
@Slf4j
@Component
public class MailJob {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private UserService userService;

    @Autowired
    private RecordService recordService;

    @Scheduled(cron = "0 0 8 * * ?")
    public void sendMail(){
        log.info("发送邮件任务开始");
        List<User> users = userService.getAll();
        //未打卡成功,未发送邮件
        /*
        * 需要发送邮件的几种情况:
        *   打卡不成功才需要发送邮件:
        *       无记录: record==null
        *       有记录:
        *           打卡失败:res==0&&send==0*/
        List<User> usersTo = users.stream().filter(user -> {
            long today = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Record record = recordService.getByDate(user.getUserId(), today);
            //record==null,发
            //record!=null, res=0
            return record == null || ("0".equals(record.getSend()) && "0".equals(record.getRes()));
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(usersTo)) {
            log.error("共{}人打卡失败",usersTo.size());
            log.info("发送失败提醒邮件");
            try {
                sendMailWithImg("2369427563@qq.com",usersTo);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            sendMailWithText(usersTo);

        }
    }

    public void sendMailWithText(List<User> failedUsers){
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("打卡失败人员名单");
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom("2369427563@qq.com");
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // message.setTo("10*****16@qq.com","12****32*qq.com");
        message.setTo("2369427563@qq.com");
        // 设置邮件抄送人，可以有多个抄送人
        //message.setCc("12****32*qq.com");
        // 设置隐秘抄送人，可以有多个
        //message.setBcc("7******9@qq.com");
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        String text = failedUsers.stream().map(User::getName).collect(Collectors.joining(","));
        message.setText(text);
        // 发送邮件
        javaMailSender.send(message);
    }

    /**
     * 发送带图片的邮件
     * @param from
     * @param toUsers
     * @throws MessagingException
     */
    public void sendMailWithImg(String from,List<User> toUsers) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("疫情打卡失败提醒");
        helper.setFrom(from);
        String[] to = toUsers.stream().map(User::getEmail).toArray(String[]::new);
        helper.setTo(to);
        //helper.setCc("37xxxxx37@qq.com");
        //helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());
        // src='cid:p01' 占位符写法 ，第二个参数true表示这是一个html文本
        helper.setText("<p>你好,今日疫情打卡失败,请手动打卡. 欢迎打赏:</p>" +
                "<p><img src='cid:p01' width=\"559\" height=\"767\"/> <span>         </span><img src='cid:p02' width=\"540\" height=\"840\"/></p>",true);

        // 第一个参数指的是html中占位符的名字，第二个参数就是文件的位置
        helper.addInline("p01",new FileSystemResource(new File("/root/health_report/pay.png")));
        helper.addInline("p02",new FileSystemResource(new File("/root/health_report/antPay.jpg")));
        javaMailSender.send(mimeMessage);
    }
}
